package com.example.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mapper.AppointmentMapper;
import com.example.mapper.SchedulingMapper;
import com.example.pojo.Appointment;
import com.example.pojo.Scheduling;
import com.example.service.SendMailService;
import com.example.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**定时任务
 *
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2022/9/17
 * @time: 19:09
 */
@Slf4j
@Configuration
@EnableScheduling
public class NormalTimerConfig {

    @Resource
    private SendMailService sendMailService;
    @Resource
    private SchedulingMapper schedulingMapper;
    @Resource
    private AppointmentMapper appointmentMapper;

    /**
     * 每晚12点30分，检查预约是否有过期的，使其失效
     */
    @Scheduled(cron = "0 30 0 * * ?")
    public void invalidApmt() {
        try {
            LambdaUpdateWrapper<Appointment> luw = new LambdaUpdateWrapper<>();
            luw.set(Appointment::getStatus, -1);
            luw.lt(Appointment::getTime, new Date());
            appointmentMapper.update(null, luw);
        } catch (Exception e) {
            //发送邮件给开发人员，ex对象发送给开发人员
            sendMailService.sendMailToManager(ExceptionUtil.getStackTraceInfo(e));
            log.error("更新过期预约任务出错: ", e);
        }
    }

    /**
     * 每晚21点00分，重新安排排班表
     */
    @Scheduled(cron = "0 0 21 * * *")
    public void reSchedule() {
        try {
            LambdaUpdateWrapper<Scheduling> luw = new LambdaUpdateWrapper<>();
            luw.set(Scheduling::getRest, 50);
            luw.set(Scheduling::getDate, DateUtil.tomorrow());
            schedulingMapper.update(null, luw);
        } catch (Exception e) {
            //发送邮件给开发人员，ex对象发送给开发人员
            sendMailService.sendMailToManager(ExceptionUtil.getStackTraceInfo(e));
            log.error("重新安排排班表任务出错: ", e);
        }
    }

}
